package com.china08.yxyapi.service.manage.tec.teaching.zujuan.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.china08.yxyapi.api.manage.tec.teaching.zujuan.previewpaper.ZujuanPaperGenerateController.DownLoadQuesModel;
import com.china08.yxyapi.api.manage.tec.teaching.zujuan.previewpaper.ZujuanPaperGenerateController.DownLoadReqModel;
import com.china08.yxyapi.api.manage.tec.teaching.zujuan.previewpaper.ZujuanPaperSaveController.PaperAnnotation;
import com.china08.yxyapi.api.manage.tec.teaching.zujuan.previewpaper.ZujuanPaperSaveController.QuestionAnnotation;
import com.china08.yxyapi.api.manage.tec.teaching.zujuan.previewpaper.ZujuanPaperSaveController.QuestionModel;
import com.china08.yxyapi.api.manage.tec.teaching.zujuan.previewpaper.ZujuanPaperSaveController.ReqModel;
import com.china08.yxyapi.entity.db.res.YxyResBookContentsKnoledges;
import com.china08.yxyapi.entity.db.yxy.YxyQuesKnow;
import com.china08.yxyapi.entity.es.ElasticYxyYxyQuesResource;
import com.china08.yxyapi.entity.mg.homework.HomeWorkQuesUsed;
import com.china08.yxyapi.entity.mg.homework.HomeworkQuesFavorite;
import com.china08.yxyapi.entity.mg.homework.HomeworkQuesGroupRelQues;
import com.china08.yxyapi.entity.mg.paper.Paper;
import com.china08.yxyapi.entity.mg.paper.PaperQues;
import com.china08.yxyapi.entity.mg.res.YxyResQues;
import com.china08.yxyapi.model.question.HomeworkQuesGroupRelQuesModel;
import com.china08.yxyapi.repository.db.YxyQuesKnowRepository;
import com.china08.yxyapi.repository.db.YxyResBookContentsKnoledgesRepository;
import com.china08.yxyapi.repository.db.YxyResBookContentsRepository;
import com.china08.yxyapi.repository.es.ElasticYxyYxyQuesResourceRespository;
import com.china08.yxyapi.repository.mg.PaperQuesRepository;
import com.china08.yxyapi.repository.mg.PaperRepository;
import com.china08.yxyapi.repository.mg.YxyResQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkQuesFavoriteRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkQuesUsedRepository;
import com.china08.yxyapi.security.profile.YxyProfile;
import com.china08.yxyapi.service.manage.tec.teaching.homework.ElasticQuesService;
import com.china08.yxyapi.service.manage.tec.teaching.zujuan.ZujuanQuestionService;
import com.china08.yxyapi.util.DownWordPaper;
import com.china08.yxyapi.util.EsQuestionUpdateUtil;
import com.china08.yxyapi.util.MongodbUtil;
import com.china08.yxyapi.util.YxyResUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;

@Service
public class ZujuanQuestionServiceImpl implements ZujuanQuestionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZujuanQuestionServiceImpl.class);

    @Autowired
    private ElasticQuesService elasticQuesService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private ElasticYxyYxyQuesResourceRespository elasticYxyYxyQuesResourceRespository;

    @Autowired
    private HomeworkQuesFavoriteRepository homeworkQuesFavoriteRepository;

    @Autowired
    private HomeworkQuesUsedRepository homeWorkQuesUsedRepository;

    @Autowired
    private YxyResBookContentsKnoledgesRepository yxyResBookContentsKnoledgesRepository;

    @Autowired
    private YxyResBookContentsRepository yxyResBookContentsRepository;

    @Autowired
    private YxyResUtil yxyResUtil;

    @Autowired
    private MongoTemplate mt;

    @Autowired
    private PaperRepository paperRepository;

    @Autowired
    private PaperQuesRepository paperQuesRepository;

    @Autowired
    private YxyQuesKnowRepository quesKnowRepository;

    @Autowired
    private HomeworkQuesUsedRepository quesUsedRepository;

    @Autowired
    private YxyResQuesRepository yxyResQuesRepository;

    @Override
    public BoolQueryBuilder get(BoolQueryBuilder boolQueryBuilder, String level, String type, String srcType) {
        // 只查询未删除的
        TermQueryBuilder deleteBuilder = new TermQueryBuilder("deleteFlag", "0");
        boolQueryBuilder.must(deleteBuilder);
        // 只能查询不是私人的
        TermQueryBuilder viewScopeBuilder = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(viewScopeBuilder);
        // 题的难度
        if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level)) {
            TermQueryBuilder builder = new TermQueryBuilder("difficultyLevel", level);
            boolQueryBuilder.must(builder);
        }
        // 题型
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            if (StringUtils.equals("6", type)) {
                List<String> notquesType = new ArrayList<String>();
                notquesType.add("1");
                notquesType.add("2");
                notquesType.add("8");
                TermsQueryBuilder builder = new TermsQueryBuilder("questionType", notquesType);
                boolQueryBuilder.mustNot(builder);
            } else {
                TermQueryBuilder builder = new TermQueryBuilder("questionType", type);
                boolQueryBuilder.must(builder);
            }
        }
        // 题的来源类型
        if (StringUtils.isNotBlank(srcType) && !StringUtils.equals("all", srcType)) {
            TermQueryBuilder builder = new TermQueryBuilder("srcType", srcType);
            boolQueryBuilder.must(builder);
        }

        return boolQueryBuilder;
    }

    /**
     * 查询page
     * 
     * @param boolQueryBuilder
     * @param pageable
     * @return
     */
    private Page<ElasticYxyYxyQuesResource> getPage(BoolQueryBuilder boolQueryBuilder, Pageable pageable) {
        SearchQuery query = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(boolQueryBuilder).build();
        Page<ElasticYxyYxyQuesResource> page = elasticsearchTemplate.queryForPage(query,
                ElasticYxyYxyQuesResource.class);
        return page;
    }

    private List<ElasticYxyYxyQuesResource> getList(BoolQueryBuilder boolQueryBuilder) {
        SearchQuery query = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).build();
        return elasticsearchTemplate.queryForList(query, ElasticYxyYxyQuesResource.class);
    }

    @Override
    public boolean checkCollectionQuestion(String userId, String quesId) {
        long count = homeworkQuesFavoriteRepository.countByTeacherIdAndQuesId(userId, quesId);
        return count > 0;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> collectionfindByMy(String phase, String subject, String userId, String level,
            String type, Pageable pageable) {

        Page<HomeworkQuesFavorite> favoritePage = null;
        if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level) && StringUtils.isNotBlank(type)
                && !StringUtils.equals("all", type)) {
            favoritePage = homeworkQuesFavoriteRepository
                    .findByTeacherIdAndStageAndSubjectAndDifficultyLevelAndQuesType(userId, phase, subject,
                            Integer.parseInt(level), type, pageable);
        } else if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level)) {
            favoritePage = homeworkQuesFavoriteRepository.findByTeacherIdAndStageAndSubjectAndDifficultyLevel(userId,
                    phase, subject, Integer.parseInt(level), pageable);
        } else if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            if (StringUtils.equals("6", type)) {
                List<String> ninType = new ArrayList<String>();
                ninType.add("1");
                ninType.add("2");
                ninType.add("8");
                favoritePage = homeworkQuesFavoriteRepository.findByTeacherIdAndStageAndSubjectAndQuesTypeNotIn(userId,
                        phase, subject, ninType, pageable);
            } else {
                favoritePage = homeworkQuesFavoriteRepository.findByTeacherIdAndStageAndSubjectAndQuesType(userId,
                        phase, subject, type, pageable);
            }
        } else {
            favoritePage = homeworkQuesFavoriteRepository.findByTeacherIdAndStageAndSubject(userId, phase, subject,
                    pageable);
        }
        long countFavorite = favoritePage.getTotalElements();
        List<String> quesIds = favoritePage.getContent().stream().map(x -> x.getQuesId()).collect(Collectors.toList());
        List<ElasticYxyYxyQuesResource> list = null;
        if (quesIds.size() > 0) {
            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            boolQueryBuilder = get(boolQueryBuilder, null, null, null);
            TermsQueryBuilder builder = new TermsQueryBuilder("id", quesIds);
            boolQueryBuilder.must(builder);
            list = getList(boolQueryBuilder);
        } else {
            list = new ArrayList<ElasticYxyYxyQuesResource>();
        }
        Page<ElasticYxyYxyQuesResource> respPage = new PageImpl<>(list, pageable, countFavorite);
        return respPage;
    }

    @Override
    public Long countQuestionUse(String quesId) {
        HomeWorkQuesUsed homeWorkQuesUsed = homeWorkQuesUsedRepository.findByQuesId(quesId);
        return homeWorkQuesUsed != null ? homeWorkQuesUsed.getUsedCount() : 0;
    }

    @Override
    public double questionDateTime(String quesId) {
        ElasticYxyYxyQuesResource elasticYxyYxyQuesResource = elasticQuesService.findByEsQuesId(quesId);
        Assert.notNull(elasticYxyYxyQuesResource, "试题未找到请刷新页面");
        String quesType = elasticYxyYxyQuesResource.getQuestionType();
        String queslevel = elasticYxyYxyQuesResource.getDifficultyLevel();
        double dateTime = 0.0;
        // 简单
        if (StringUtils.equals("1", queslevel)) {
            // 单选
            if (StringUtils.equals("1", quesType)) {
                dateTime = 1;
            }
            // 多选
            else if (StringUtils.equals("8", quesType)) {
                dateTime = 1.5;
            }
            // 填空
            else if (StringUtils.equals("2", quesType)) {
                dateTime = 1;
            }
            // 解答
            else {
                dateTime = 3;
            }
        }
        // 中等
        else if (StringUtils.equals("2", queslevel)) {
            // 单选
            if (StringUtils.equals("1", quesType)) {
                dateTime = 2;
            }
            // 多选
            else if (StringUtils.equals("8", quesType)) {
                dateTime = 2.5;
            }
            // 填空
            else if (StringUtils.equals("2", quesType)) {
                dateTime = 2;
            }
            // 解答
            else {
                dateTime = 5;
            }
        }
        // 困难
        else if (StringUtils.equals("3", queslevel)) {
            // 单选
            if (StringUtils.equals("1", quesType)) {
                dateTime = 4;
            }
            // 多选
            else if (StringUtils.equals("8", quesType)) {
                dateTime = 4.5;
            }
            // 填空
            else if (StringUtils.equals("2", quesType)) {
                dateTime = 3;
            }
            // 解答
            else {
                dateTime = 8;
            }
        }
        return dateTime;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> questionFindByBookcontentAndLevelAndTypeAndUse(String bookcontent,
            String level, String type, String srcType, String userId, String bookId, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 基本查询
        boolQueryBuilder = get(boolQueryBuilder, level, type, srcType);
        if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all", bookcontent)) {
            // 目录查询
            boolQueryBuilder = questionFindByBookcontent(boolQueryBuilder, bookcontent);
        } else {
            // 按书查询
            List<String> bookContent = yxyResBookContentsRepository.findIdByBookId(bookId);
            if (bookContent.size() > 0) {
                List<YxyResBookContentsKnoledges> bookContentsKnoledges = yxyResBookContentsKnoledgesRepository
                        .findByBookContentIdIn(bookContent);
                if (bookContentsKnoledges.size() > 0) {
                    List<Integer> knowIds = bookContentsKnoledges.stream().map(x -> x.getKnowledgeId())
                            .collect(Collectors.toList());
                    TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", knowIds);
                    boolQueryBuilder.must(builder);
                } else {
                    TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", new ArrayList<>());
                    boolQueryBuilder.must(builder);
                }
            } else {
                TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", new ArrayList<>());
                boolQueryBuilder.must(builder);
            }
        }
        Page<ElasticYxyYxyQuesResource> page = getPage(boolQueryBuilder, pageable);
        return page;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> questionFindByKnowAndLevelAndTypeAndUse(String know, String level,
            String type, String use, String userId, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (StringUtils.isNotBlank(know) && !StringUtils.equals("all", know)) {
            TermQueryBuilder builder = new TermQueryBuilder("knowFullIds", Integer.parseInt(know));
            boolQueryBuilder.must(builder);
        }
        // 基本查询
        boolQueryBuilder = get(boolQueryBuilder, level, type, use);
        Page<ElasticYxyYxyQuesResource> page = getPage(boolQueryBuilder, pageable);
        return page;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> questionFindByMyGroupId(String schoolId, String userId, String groupId,
            String level, String type, String phase, String subject, Pageable pageable) {
        DBCollection collection = mt.getCollection(mt.getCollectionName(HomeworkQuesGroupRelQues.class));
        BasicDBObject dbObject = new BasicDBObject();
        dbObject.put("school_id", schoolId);
        dbObject.put("teacher_id", userId);
        dbObject.put("group_id", groupId);
        dbObject.put("stage", phase);
        dbObject.put("subject", subject);
        if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level)) {
            dbObject.put("defficulty_level", Integer.parseInt(level));
        }
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            if (StringUtils.equals("6", type)) {
                List<String> ninTypeList = new ArrayList<String>();
                ninTypeList.add("1");
                ninTypeList.add("2");
                ninTypeList.add("8");
                BasicDBObject ninType = new BasicDBObject("$nin", ninTypeList);
                dbObject.put("ques_type", ninType);
            } else {
                dbObject.put("ques_type", type);
            }
        }
        Page<HomeworkQuesGroupRelQuesModel> groupRelQuesModelPage = MongodbUtil.getPage(collection, dbObject, pageable,
                HomeworkQuesGroupRelQuesModel.class);
        List<String> quesIds = new ArrayList<String>();
        for (HomeworkQuesGroupRelQuesModel homeworkQuesGroupRelQuesModel : groupRelQuesModelPage) {
            quesIds.add(homeworkQuesGroupRelQuesModel.getQues_id());
        }
        List<ElasticYxyYxyQuesResource> respList = new ArrayList<ElasticYxyYxyQuesResource>();
        if (quesIds.size() > 0) {
            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            TermsQueryBuilder builder = new TermsQueryBuilder("id", quesIds);
            boolQueryBuilder.must(builder);
            TermsQueryBuilder delBuilder = new TermsQueryBuilder("deleteFlag", "0");
            boolQueryBuilder.must(delBuilder);
            respList = getList(boolQueryBuilder);
        }
        Page<ElasticYxyYxyQuesResource> respPage = new PageImpl<ElasticYxyYxyQuesResource>(respList, pageable,
                groupRelQuesModelPage.getTotalElements());
        return respPage;
    }

    @Override
    public BoolQueryBuilder questionFindByBookcontent(BoolQueryBuilder boolQueryBuilder, String bookcontent) {
        // 找到这个目录下的所有子目录
        List<String> bookcontentList = yxyResUtil.findTocByTocParent(bookcontent);
        List<YxyResBookContentsKnoledges> bookContentsKnoledges = yxyResBookContentsKnoledgesRepository
                .findByBookContentIdIn(bookcontentList);
        if (bookContentsKnoledges.size() > 0) {
            List<Integer> knowIds = bookContentsKnoledges.stream().map(x -> x.getKnowledgeId())
                    .collect(Collectors.toList());
            TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", knowIds);
            boolQueryBuilder.must(builder);
        } else {
            List<Integer> knoids = new ArrayList<Integer>();
            TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", knoids);
            boolQueryBuilder.must(builder);
        }
        return boolQueryBuilder;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> findMyUpload(String phase, String subject, String userId, String level,
            String type, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermsQueryBuilder builderUserId = new TermsQueryBuilder("createdBy", userId);
        boolQueryBuilder.must(builderUserId);
        Page<ElasticYxyYxyQuesResource> page = getPage(boolQueryBuilder, pageable);
        return page;
    }

    @Override
    public List<Integer> getBookContentKnowList(String bookcontent, List<Integer> knowList) {
        Set<Integer> set = new HashSet<Integer>();
        List<String> bookcontentList = yxyResUtil.findTocByTocParent(bookcontent);
        if (bookcontentList.size() > 0) {
            List<YxyResBookContentsKnoledges> bookContentsKnoledges = yxyResBookContentsKnoledgesRepository
                    .findByBookContentIdIn(bookcontentList);
            List<Integer> bcKnowList = bookContentsKnoledges.stream().map(x -> x.getKnowledgeId())
                    .collect(Collectors.toList());
            set.addAll(bcKnowList);
            set.retainAll(knowList);
            bcKnowList.clear();
            bcKnowList.addAll(set);
        }
        return new ArrayList<Integer>(set);
    }

    @Override
    public List<Integer> getKnowLedgeKnowList(String know, List<Integer> knowList) {
        Set<Integer> set = new HashSet<Integer>();
        List<Integer> knowIntegers = yxyResUtil.findTocByTocKnowParent(Integer.parseInt(know));
        if (knowList.size() > 0) {
            set.addAll(knowIntegers);
            set.retainAll(knowList);
            knowList.clear();
            knowList.addAll(set);
        }
        return new ArrayList<Integer>(set);
    }

    @Override
    public void FavQuesOrCancelQues(String userId, String schoolId, String quesId) {
        ElasticYxyYxyQuesResource elasticYxyYxyQuesResource = elasticYxyYxyQuesResourceRespository.findById(quesId);
        Assert.notNull(elasticYxyYxyQuesResource, "试题不存在请刷新页面");
        HomeworkQuesFavorite favorite = homeworkQuesFavoriteRepository.findByQuesIdAndTeacherId(quesId, userId);
        if (favorite == null) {
            favorite = new HomeworkQuesFavorite();
            favorite.setCreatedBy(userId);
            favorite.setLastModifiedBy(userId);
            favorite.setTeacherId(userId);
            favorite.setSchoolId(schoolId);
            favorite.setStage(elasticYxyYxyQuesResource.getPhase());
            favorite.setSubject(elasticYxyYxyQuesResource.getSubject());
            favorite.setQuesId(elasticYxyYxyQuesResource.getId());
            List<Integer> knowIds = elasticYxyYxyQuesResource.getKnowledgeIds();
            String know = "";
            if (knowIds != null && knowIds.size() > 0) {
                know = StringUtils.join(knowIds, ",");
            }
            favorite.setKnowIds(know);
            favorite.setQuesType(elasticYxyYxyQuesResource.getQuestionType());
            favorite.setDifficultyLevel(Integer.parseInt(elasticYxyYxyQuesResource.getDifficultyLevel()));
            homeworkQuesFavoriteRepository.save(favorite);
        } else {
            homeworkQuesFavoriteRepository.delete(favorite);
        }

        // 更新收藏次数
        Long favoriteCount = homeworkQuesFavoriteRepository.countByQuesId(quesId);
        YxyResQues yxyResQues = yxyResQuesRepository.findById(quesId);
        yxyResQues.setHomeworkFavoriteCount(favoriteCount);
        yxyResQuesRepository.save(yxyResQues);
        // 发消息更新es索引
        EsQuestionUpdateUtil.updateEsQuestion(quesId);
    }

    @Override
    public void SavePaper(ReqModel reqModel, YxyProfile yxyProfile) {
        // 试卷id
        String paperId = reqModel.paperId;
        // 试卷主标题
        String title = reqModel.title1;
        Integer titleFlag = null;
        // 副标题
        String subTitle = reqModel.title2;
        // 副标题 标识
        Integer subTitleFlag = null;
        // 装订线 标识
        Integer bindingFlag = null;
        // 保密标记标识
        Integer secretLineFlag = null;
        // 试卷信息栏
        String paperInfo = reqModel.title3;
        // 试卷信息栏标识
        Integer paperInfoFlag = null;
        // 考生输入栏
        String studentColumn = reqModel.title4;
        // 考生输入栏 标识
        Integer studentColumnFlag = null;
        // 誉分栏标识
        Integer scoreColumnFlag = null;
        // 注意事项标识
        Integer attentionFlag = null;
        // 分卷及注释
        List<PaperAnnotation> list1 = reqModel.paperAnnotationlist;
        // 分卷及注释标识
        Integer paperAnnotationFlag = null;
        // 大题注释及分数
        List<QuestionAnnotation> list2 = reqModel.questionAnnotationlist;
        // 大题注释及分数标识
        Integer questionAnnotationFlag = null;
        // 大题评分区标识
        Integer questionScoreFlag = null;
        // 学段id
        String phaseId = reqModel.stage;
        // 学段名称
        String phaseName = reqModel.stageName;
        // 学科id
        String subjectId = reqModel.subject;
        // 学科名称
        String subjectName = reqModel.subjectName;

        // 试卷的基本的配置
        List<String> checkList = reqModel.checkList;

        // 获取标识
        if (CollectionUtils.isNotEmpty(checkList)) {
            // 主标题的标识
            if (checkList.contains("1")) {
                titleFlag = 1;
            }
            // 副标题标识
            if (checkList.contains("2")) {
                subTitleFlag = 1;
            }
            // 装订线的标识
            if (checkList.contains("3")) {
                bindingFlag = 1;
            }
            // 保密标记标识
            if (checkList.contains("4")) {
                secretLineFlag = 1;
            }
            // 试卷信息栏标识
            if (checkList.contains("5")) {
                paperInfoFlag = 1;
            }
            // 考生输入栏标识
            if (checkList.contains("6")) {
                studentColumnFlag = 1;
            }
            // 誉分栏标识
            if (checkList.contains("7")) {
                scoreColumnFlag = 1;
            }
            // 注意事项标识
            if (checkList.contains("8")) {
                attentionFlag = 1;
            }
            // 分卷及注释标识
            if (checkList.contains("9")) {
                paperAnnotationFlag = 1;
            }
            // 大题注释及分数标识
            if (checkList.contains("10")) {
                questionAnnotationFlag = 1;
            }
            // 大题评分区标识
            if (checkList.contains("11")) {
                questionScoreFlag = 1;
            }
        }

        Paper paper = paperRepository.findById(paperId);
        if (paper == null) {
            paper = new Paper();
        }
        paper.setUserId(yxyProfile.getId());
        paper.setUserNick(yxyProfile.getUserNick());
        paper.setSchoolId(yxyProfile.getSchoolId());
        paper.setSchoolNick(yxyProfile.getSchoolName());
        paper.setTitle(title);
        paper.setTitleFlag(titleFlag);
        paper.setSubTitle(subTitle);
        paper.setSubTitleFlag(subTitleFlag);
        paper.setBindingFlag(bindingFlag);
        paper.setSecretLineFlag(secretLineFlag);
        paper.setPaperInfo(paperInfo);
        paper.setPaperInfoFlag(paperInfoFlag);
        paper.setStudentColumn(studentColumn);
        paper.setStudentColumnFlag(studentColumnFlag);
        paper.setScoreColumnFlag(scoreColumnFlag);
        paper.setAttentionFlag(attentionFlag);
        // 分卷及注释
        Map<Integer, String> map1 = list1.stream()
                .collect(Collectors.toMap(PaperAnnotation::getNum, PaperAnnotation::getPaperAnnotation));
        paper.setPaperAnnotation(map1);
        paper.setPaperAnnotationFlag(paperAnnotationFlag);
        // 大题及注释
        Map<Integer, String> map2 = list2.stream()
                .collect(Collectors.toMap(QuestionAnnotation::getNum, QuestionAnnotation::getQuestionAnnotation));
        paper.setQuestionAnnotation(map2);
        paper.setQuestionAnnotationFlag(questionAnnotationFlag);
        paper.setQuestionScoreFlag(questionScoreFlag);
        paper.setPhaseId(phaseId);
        paper.setPhaseName(phaseName);
        paper.setSubjectId(subjectId);
        paper.setSubjectName(subjectName);
        paper = paperRepository.save(paper);
        Integer count = paperQuesRepository.countByPaperId(paper.getId());
        if (count > 0) {
            paperQuesRepository.deleteByPaperId(paper.getId());
        }
        // 保存试题
        PaperQues paperQues = null;
        List<PaperQues> list = new ArrayList<PaperQues>();
        // 试题的使用次数
        HomeWorkQuesUsed quesUsed = null;
        List<HomeWorkQuesUsed> quesUsedList = new ArrayList<HomeWorkQuesUsed>();
        int order = 1;
        List<QuestionModel> queslist = reqModel.quesIdList;
        for (QuestionModel questionModel : queslist) {
            // 题的使用次数
            quesUsed = quesUsedRepository.findByQuesId(questionModel.quesId);
            if (quesUsed != null) {
                quesUsed.setUsedCount(quesUsed.getUsedCount() + 1);
            } else {
                quesUsed = new HomeWorkQuesUsed();
                quesUsed.setQuesId(questionModel.quesId);
                quesUsed.setUsedCount(1l);
            }
            quesUsedList.add(quesUsed);
            // 更新mongodb题的使用次数
            YxyResQues yxyResQues = yxyResQuesRepository.findById(questionModel.quesId);
            yxyResQues.setHomeworkUseCount(quesUsed.getUsedCount());
            yxyResQuesRepository.save(yxyResQues);

            paperQues = new PaperQues();
            List<Integer> knowId = questionModel.know;
            paperQues.setKnowId(knowId);
            List<YxyQuesKnow> knows = quesKnowRepository.findByIdIn(knowId);
            List<String> knowNamesList = knows.stream().map(x -> x.getName()).collect(Collectors.toList());
            paperQues.setKnowName(knowNamesList);
            paperQues.setScore(questionModel.point);
            paperQues.setOrder(order);
            order++;
            paperQues.setQuesId(questionModel.quesId);
            // 题型
            paperQues.setQuesType(questionModel.quesType);
            paperQues.setPaperId(paper.getId());
            list.add(paperQues);
        }
        quesUsedRepository.save(quesUsedList);
        paperQuesRepository.save(list);

        // 发消息更新试题
        List<String> quesIdList = queslist.stream().map(x -> x.quesId).collect(Collectors.toList());
        EsQuestionUpdateUtil.updateEsQuestionList(quesIdList);
    }

    @Override
    public String DownLoadPaper(DownLoadReqModel reqModel, String dowString) throws Exception {
        List<DownLoadQuesModel> queslist = reqModel.queslist;
        // 单选
        List<DownLoadQuesModel> list1 = new ArrayList<DownLoadQuesModel>();
        // 填空
        List<DownLoadQuesModel> list2 = new ArrayList<DownLoadQuesModel>();
        // 多选
        List<DownLoadQuesModel> list3 = new ArrayList<DownLoadQuesModel>();
        // 解答
        List<DownLoadQuesModel> list4 = new ArrayList<DownLoadQuesModel>();
        for (DownLoadQuesModel downLoadQuesModel : queslist) {
            String questionType = downLoadQuesModel.quesType;
            if (StringUtils.equals("1", questionType)) {
                list1.add(downLoadQuesModel);
            } else if (StringUtils.equals("2", questionType)) {
                list2.add(downLoadQuesModel);
            } else if (StringUtils.equals("8", questionType)) {
                list3.add(downLoadQuesModel);
            } else {
                list4.add(downLoadQuesModel);
            }
        }
        // 注意事项
        String attention = "1、答题前填写好自己的姓名、班级、学号等信息。</br>"//
                + "2、请用黑色水笔书写。</br>" //
                + "3、请将答案正确填写在答题卡上。</br>";
        // 基本设置
        List<String> checkList = reqModel.checkList;
        DownWordPaper downWordPaper = new DownWordPaper();
        downWordPaper.setPaperType(reqModel.paperType);
        downWordPaper.setPaperSize(reqModel.paperSize);
        downWordPaper.setBasicSettingList(checkList);
        downWordPaper.setMainTitle(reqModel.title1);
        downWordPaper.setSubTitle(reqModel.title2);
        downWordPaper.setPaperInfo(reqModel.title3);
        downWordPaper.setStudentInfo(reqModel.title4);
        downWordPaper.setInstructionFirst(reqModel.title5);
        downWordPaper.setInstructionTwo(reqModel.title6);
        downWordPaper.setNotesFirst(reqModel.title7);
        downWordPaper.setNotesTwo(reqModel.title8);
        downWordPaper.setNotesThree(reqModel.title9);
        downWordPaper.setNotesFour(reqModel.title10);
        downWordPaper.setAttentionInfo(attention);
        downWordPaper.setDownloadDir(dowString);
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        // String format = sdf.format(new Date());
        // String paperName = "下载试卷-" + format + ".docx";
        String paperName = reqModel.title1 + System.currentTimeMillis() + ".docx";
        downWordPaper.setPaperName(paperName);
        downWordPaper.setDanxuan(list1);
        downWordPaper.setDuoxuan(list3);
        downWordPaper.setTiankong(list2);
        downWordPaper.setJieda(list4);
        // 生成试卷
        LOGGER.info("=======================================开始执行生成word方法");
        downWordPaper.GeneratePaper("docx");
        LOGGER.info("=======================================结束执行生成word方法");
        return paperName;
    }
}
